package com.letv.ads.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.letv.adlib.managers.status.ad.AdStatusManager;
import com.letv.adlib.managers.status.ad.IAdStatusManager;
import com.letv.adlib.sdk.types.AdElement;
import com.letv.adlib.sdk.types.AdElementMime;
import com.letv.adlib.sdk.types.AdElementSplash;
import com.letv.adlib.view.SplashVideoView;
import com.letv.ads.AdsManager;
import com.letv.android.sdk.R;
import com.letv.ads.util.AdViewClickListener;
import com.letv.ads.util.AdsUtils;
import com.letv.ads.util.IBootVideoPlayCallback;
import com.letv.ads.util.LogInfo;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by leiyao on 14-9-22.
 */
public class VideoAdView extends LinearLayout implements View.OnClickListener {
    private final static String TAG = "bootVideo";
    private boolean hasPlayed = false;
    private boolean hasInited = false;
    private boolean isFirstPlay = true;
    private final int REFRESH_COUNTDOWN = 1;
    private final int STOP_VIDEO_AD = 2;
    private final int DISPOSE_VIDEO_AD = 3;
    private final int SHOW_VIDEO_AD = 4;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_COUNTDOWN:
                    refreshCountdown();
                    break;
                case STOP_VIDEO_AD:
                    stopVideoAd(true);
                    break;
                case DISPOSE_VIDEO_AD:
                    doDispose();
                    break;
                case SHOW_VIDEO_AD:
                    showBootCountdown();
                    break;
                default:
                    break;
            }
        }
    };
    private final int STOP_VIDEO_DELAY = 400;
    private final int REFRESH_COUNTDOWN_DELAY = 1000;
    /**
     * 广告素材对象
     */
    private AdElementSplash mAdInfo;
    private IAdStatusManager adStatusManager;
    private IBootVideoPlayCallback callback;
    private AudioManager mAudioManager;
    private int WAIT_TIME_COUNT = 3;
    private int waitTimeCountElapsed = 0;
    private boolean hasClick = true;
    /**
     * 需要跳转播放的点击，回调给主程序
     */
    private AdViewClickListener listener;
    private int curVoice,oldVoice;
    private Timer timer;
    /**
     * 保持尺寸，控制requestLayout是否响应
     */
    private boolean keepSize;
    /**
     * 是否能关闭
     */
    private boolean canClose;
    /**
     * 广告视频控件
     */
    private SplashVideoView mVvVideoView;
    private TextView mTvCountdownText;
    private ImageView mIvMuteBtn;
    private TextView mTvSkipAd;
    private RelativeLayout mRlLayout;
    private boolean isVideoAdPaused = false;
    private android.graphics.Typeface mTypeface;
    private int curPosition = 0;

    public VideoAdView(Context context) {
        super(context);
        init(context);
//        requestAd();
    }

    public VideoAdView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getAttrs(context, attrs);
        init(context);
//        requestAd();
    }

    /**
     * 得到广告点击回调
     */
    public AdElementMime getAdInfo() {
        return mAdInfo;
    }

    /**
     * 如果请求过程和显示过程分离的操作，可以直接传入广告物料进行显示和曝光（如：首页焦点图广告）
     *
     * @return 返回是否初始化成功
     */
    public boolean setAdInfo(AdElementSplash mAdInfo, IBootVideoPlayCallback callback, DisplayMetrics displayMetrics, AudioManager audioManager, AdViewClickListener listener) {
        if (hasInited) return false;
        hasInited = true;
        this.mAdInfo = mAdInfo;
        this.callback = callback;
        timeElapsedCountForBootVideo();
        if (mAdInfo != null) {
            fill(mAdInfo);
        }
        if (this.mVvVideoView != null) {
            this.mVvVideoView.WIDTH = displayMetrics.widthPixels;
            this.mVvVideoView.HEIGHT = displayMetrics.heightPixels;
        }
        adStatusManager = new AdStatusManager(mAdInfo);
        mAudioManager = audioManager;
        if (mAudioManager != null) {
            oldVoice = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            curVoice = 0;
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, curVoice, 0);
        }
        //设置倒计时初始文字及字体
        mTvCountdownText.setTypeface(mTypeface);
        this.listener = listener;
        mTvCountdownText.setText(mAdInfo.duration + "");
        return true;
    }

    /**
     * 终止播放
     * @param isForceClose
     * @return
     */
    public boolean stopAd(boolean isForceClose) {
        if (this.mVvVideoView == null || !hasInited)
            return false;
        hasInited = false;
        hasPlayed = false;
        isFirstPlay = true;
        this.mVvVideoView.setOnPreparedListener(null);
        this.mVvVideoView.setOnCompletionListener(null);
        this.mVvVideoView.setOnErrorListener(null);

        LogInfo.log("bootPic", "isForceClose=" + isForceClose);
//        this.videoView.pause();
        if (isForceClose)
            this.mVvVideoView.pause();
        this.changeVoice(oldVoice);
        mAudioManager = null;
        return true;
    }

    /**
     * 暂停播放
     */
    public void pause() {
        if (this.mVvVideoView == null || !hasInited) return;
        if (this.isPlaying()) {
            curPosition = this.mVvVideoView.getCurrentPosition();
        }
        this.mVvVideoView.pause();
        LogInfo.log("bootPic", "curPos hisotry:" + curPosition);
    }

    /**
     * 继续播放
     */
    public void resume() {
        if (this.mVvVideoView == null || !this.hasInited) return;
//        if (curPosition != 0 && hasVideoView()){
        LogInfo.log("bootPic", "curPos seekTo:" + curPosition);
        this.mVvVideoView.seekTo(curPosition);
        this.mVvVideoView.start();
        if (callback != null)
            callback.onResume();
//        }
    }

    /**
     * 加载失败
     */
    public void onLoadError() {
        LogInfo.log("bootPic", "load boot video timeout");
        if (this.mVvVideoView == null) return;
        if(adStatusManager!= null) {
            adStatusManager.onAdLoadError();
        }
    }

    /**
     * 获取当前播放进度
     * @return
     */
    public int getCurrentPosition() {
        if (this.mVvVideoView == null) return -1;
        return this.mVvVideoView.getCurrentPosition();
    }

    /**
     * 更改声音
     * @param voice
     */
    private void changeVoice(int voice) {
        if (this.mVvVideoView == null) return;
        this.mVvVideoView.setVoice(voice, getContext());
        if (mAudioManager != null) {
            if (voice < 0) voice = 0;
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, voice, 0);
        }
    }

    public void onVoiceKeyDown(){
        if (mAudioManager != null) {
            curVoice = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            mIvMuteBtn.setImageResource(curVoice <= 0 ? R.drawable.letv_boot_mute : R.drawable.letv_boot_not_mute);
        }
    }
    /**
     * 清理操作
     */
    public void dispose() {
        if (handler != null){
            handler.sendEmptyMessageDelayed(DISPOSE_VIDEO_AD,STOP_VIDEO_DELAY);
        }
    }

    public void doDispose() {
        LogInfo.log(TAG,"hadInied:"+hasInited+",this.vv:"+this.mVvVideoView);
        if (this.mVvVideoView != null) {
            this.mVvVideoView.stopPlayback();
            this.mVvVideoView.setVisibility(GONE);
            this.mVvVideoView = null;
            this.mRlLayout.setVisibility(GONE);
            if(adStatusManager!= null) {
                adStatusManager.onAdPlayComplete();
                adStatusManager = null;
            }
        }
    }

    /**
     * 是否正在播放
     * @return
     */
    public boolean isPlaying() {
        if (this.mVvVideoView == null) return false;
        return hasVideoView() && this.mVvVideoView.isPlaying();
    }

    /**
     * 是否有开机视频
     * @return
     */
    public boolean hasVideoView() {
        return this.hasInited;
    }

    /**
     * 获取声音
     * @param context
     * @return
     */
    public int getVoice(Context context) {

        if (this.mVvVideoView == null) return -2;
        return this.mVvVideoView.getVoice(context);
    }

    /**
     * 显示布局
     */
    public void showLayout(){
        this.setVisibility(View.VISIBLE);
    }

    /**
     * 终止视频播放
     * @param isForceClose
     */
    public void stopVideoAd(boolean isForceClose){
        isVideoAdPaused = true;
        if (stopAd(isForceClose)){
            LogInfo.log(TAG, "-----stopAd,isVideoAdPause=" + isVideoAdPaused);
            if (callback != null){
                callback.onStop();
            }
        }
    }


    /**
     * 刷新倒计时
     */
    public void refreshCountdown() {
        if (mTvCountdownText != null) {
            if (isVideoAdPaused) return;
            if (WAIT_TIME_COUNT - waitTimeCountElapsed > 0) {
                mTvCountdownText.setText((WAIT_TIME_COUNT - waitTimeCountElapsed) + "");
            }
            LogInfo.log(TAG, "WAIT_TIME_COUNT:" + WAIT_TIME_COUNT + ",position:" + waitTimeCountElapsed + ",");
            waitTimeCountElapsed++;
            if (waitTimeCountElapsed <= WAIT_TIME_COUNT) {
                if (waitTimeCountElapsed == WAIT_TIME_COUNT) {
                    if (!isVideoAdPaused) {
                        handler.sendEmptyMessageDelayed(STOP_VIDEO_AD, STOP_VIDEO_DELAY);
                        isVideoAdPaused = true;
                    }
                } else {
                    handler.sendEmptyMessageDelayed(REFRESH_COUNTDOWN, REFRESH_COUNTDOWN_DELAY);
                }
            } else {
                if (!isVideoAdPaused) {
                    handler.sendEmptyMessageDelayed(STOP_VIDEO_AD, STOP_VIDEO_DELAY);
                    isVideoAdPaused = true;
                }
            }
        }
    }

    /**
     * 显示启动视频的倒计时
     */
    public void showBootCountdown() {
        mIvMuteBtn.setVisibility(View.VISIBLE);
        mTvCountdownText.setVisibility(View.VISIBLE);
        this.setVisibility(View.VISIBLE);
    }

    public void stopBootVideo(){
        if (stopAd(true)) {
            if (callback != null) {
                callback.onStop();
            }
//        dispose();
            if (handler != null)
                handler.removeMessages(REFRESH_COUNTDOWN);
        }
    }

    /**
     * 显示启动视频的倒计时
     */
    public void showBootCountdownDelay(int msec) {
       if (handler!=null){
           handler.sendEmptyMessageDelayed(SHOW_VIDEO_AD,msec);
       }
    }


    private void init(Context context) {
        inflate(context, R.layout.letv_ad_video_view, this);
        findView();
        mTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/ads_digital.ttf");
        if (keepSize) {
            setVisibility(INVISIBLE);
        } else {
            setVisibility(GONE);
        }
    }

    /**
     * 初始化属性
     */
    private void getAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.adview);
        canClose = ta.getBoolean(R.styleable.adview_canClose, true);
        keepSize = ta.getBoolean(R.styleable.adview_keepSize, true);

        ta.recycle();
    }

    /**
     * 初始化控件
     */
    private void findView() {
        mVvVideoView = (SplashVideoView) findViewById(R.id.ad_video);
        mTvCountdownText = (TextView) findViewById(R.id.waitting_time);

        mTvSkipAd = (TextView) findViewById(R.id.skip_ad);
        mTvSkipAd.setOnClickListener(this);

        mIvMuteBtn = (ImageView) findViewById(R.id.ad_boot_mute);
        mIvMuteBtn.setOnClickListener(this);

        mRlLayout = (RelativeLayout) findViewById(R.id.ad_boot_layout);
    }

    /**
     * 填充物料，及绘制
     */
    private void fill(final AdElementSplash adInfo) {
        LogInfo.log("bootPic", "fill,hasPlayed=" + hasPlayed);
        if (hasPlayed) return;
        hasPlayed = true;
        if (adInfo != null) {
            /*adInfo.clickShowType = AdElement.AdClickShowType.SHOW_EnterVideoPlayer.value();
            adInfo.vid = "22165253";
            adInfo.pid = "10002011";*/
            mAdInfo = adInfo;
            WAIT_TIME_COUNT = adInfo.duration;
            mVvVideoView.setVideoPath(adInfo.localPath);
            mVvVideoView.requestFocus();
            mVvVideoView.start();

            mVvVideoView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        if (hasClick()) {
                            LogInfo.log(TAG, "CLICK TO JUMP SO STOP VIDEO VIEW!");
                        stopBootVideo();
                        }
                    }
                    return true;
                }
            });

            mVvVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    if (mVvVideoView == null) {
                        LogInfo.log("bootPic", "setOnPreparedListener,videoView == null=" + (mVvVideoView == null) + ",hasPlayed=" + hasPlayed);
                        return;
                    }

                    if (callback != null) {
                        if (isFirstPlay) {
                            mRlLayout.setVisibility(VISIBLE);
                            callback.onStart();
                            onStart();
                            adStatusManager.onAdPlayStart();
                        } else {
                            callback.onResume();
                        }
                    }
//                    if (!cancel)
//                        mediaPlayer.start();
                    isFirstPlay = false;
                }
            });

            mVvVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
                    if (mVvVideoView == null) return true;
                    if (callback != null) callback.onError();
                    onLoadError();
                    VideoAdView.this.onError();
                    return true;
                }
            });

            mVvVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    if (mVvVideoView == null) return;
                    LogInfo.log("bootPic", "setOnCompletionListener,videoView == null=" + (mVvVideoView == null) + ",hasPlayed=" + hasPlayed);
                    if (callback != null) callback.onComplate(true);
                }
            });

        }
    }

    /**
     * 判断点击时间是否需要响应，没哟响应回调到主程序
     */
    public boolean hasClick() {
        if (getVisibility() != VISIBLE) {
            hasClick = false;
        }
        if (hasClick) {
            if (mAdInfo.clickShowType == AdElement.AdClickShowType.SHOW_EnterVideoPlayer.value()) { // 视频广告，回调主程序
                if (listener != null) {
                    listener.onClick(mAdInfo.clickShowType, mAdInfo.pid, mAdInfo.vid);

                    /**
                     * 点击统计
                     * */
                    AdStatusManager statusMgr = new AdStatusManager(mAdInfo);
                    statusMgr.onAdClicked();
                }
            } else if (mAdInfo.clickShowType == AdElement.AdClickShowType.SHOW_EnterLivePlayer.value()) {
                if (listener != null) {
                    listener.onClick(mAdInfo.clickShowType, mAdInfo.sid, mAdInfo.streamURL);

                    /**
                     * 点击统计
                     * */
                    AdStatusManager statusMgr = new AdStatusManager(mAdInfo);
                    statusMgr.onAdClicked();
                }
            } else if (mAdInfo.clickShowType == AdElement.AdClickShowType.SHOW_InstallAPK.value()) {
                AdsManager.getInstance().downloadAndInstallApk(mAdInfo.getClickThrough(), mAdInfo.text);
                /**
                 * 点击统计
                 * */
                AdStatusManager statusMgr = new AdStatusManager(mAdInfo);
                statusMgr.onAdClicked();

            } else if (mAdInfo.clickShowType == AdElement.AdClickShowType.SHOW_NoAction.value()){
                hasClick = false;
                /**
                 * 点击统计
                 * */
                AdStatusManager statusMgr = new AdStatusManager(mAdInfo);
                statusMgr.onAdClicked();
            } else {// 图片广告，打开浏览器
                clickGotoWeb();
            }
        }
        return hasClick;
    }

    /**
     * 点击广告跳转到系统浏览器,并请求点击曝光地址和第三方点击曝光地址
     */
    private void clickGotoWeb() {
        if (AdsUtils.checkClickEvent()) {
            if (mAdInfo.clickShowType == AdElement.AdClickShowType.SHOW_ExternalWebBrowser.value() || mAdInfo.clickShowType == AdElement.AdClickShowType.SHOW_InternalWebView.value()) {
                if (!TextUtils.isEmpty(mAdInfo.getClickThrough())) {
                    AdsUtils.gotoWeb(getContext(), mAdInfo);
                }
            }
            /**
             * 点击统计
             * */
            AdStatusManager statusMgr = new AdStatusManager(mAdInfo);
            statusMgr.onAdClicked();
        }
    }

    /**
     * 定时器,防止开机大图加载时间过长
     */
    private void timeElapsedCountForBootVideo() {
        if (callback != null) {
            timer = new Timer();
            callback.setLoadTimeout(false);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    callback.setLoadTimeout(true);
                    onLoadError();
                    handler.sendEmptyMessage(STOP_VIDEO_AD);
                    handler.sendEmptyMessageDelayed(DISPOSE_VIDEO_AD, STOP_VIDEO_DELAY);
                }
            }, 3000);
        }
    }

    /**
     * 停止超时计时
     */
    public void timeElapsedCancel(){
        if (callback != null) {
            if (timer != null) {
                timer.cancel();
            }
            callback.setLoadTimeout(false);
            timer = null;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mTvSkipAd){
            LogInfo.log(TAG,"click to stop ad !");
            stopBootVideo();
        }else if (v == mIvMuteBtn){
            if (curVoice == 0) {
                mIvMuteBtn.setImageResource(R.drawable.letv_boot_not_mute);
                curVoice = oldVoice == 0 ? 5 : oldVoice;
                changeVoice(curVoice);
            }else{
                mIvMuteBtn.setImageResource(R.drawable.letv_boot_mute);
                curVoice = 0;
                changeVoice(curVoice);
            }
            //
        }
    }

    private void onStart(){
        LogInfo.log("bootPic", "onstart");
        timeElapsedCancel();
        if (Build.VERSION.SDK_INT >= 11) {
            showBootCountdown();
        } else {
            // 延时处理一下，否则会有残影
            showBootCountdownDelay(200);
        }
        refreshCountdown();
    }
    private void onError() {
        LogInfo.log("bootPic", "onError");
        stopVideoAd(false);
        isVideoAdPaused = true;
        timeElapsedCancel();
    }
    private void onComplate() {
        LogInfo.log("bootPic", "onComplate");
        stopVideoAd(false);
        isVideoAdPaused = true;
//            animProcess();
    }



}
